package cc.idoone.zipkin;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
public class ZipkinController {

    @Autowired
    private CloseableHttpClient httpClient;

    @GetMapping("/service1")
    public String service() throws Exception {
        Random random = new Random();
        int sleep = random.nextInt(100);
        TimeUnit.MILLISECONDS.sleep(sleep);

        HttpGet get = new HttpGet("http://localhost:5002/service2");
        CloseableHttpResponse response = httpClient.execute(get);
        return EntityUtils.toString(response.getEntity(), "utf-8");
    }

    @GetMapping("/service2")
    public String service2() throws Exception {
        Random random = new Random();
        int sleep = random.nextInt(100);
        TimeUnit.MILLISECONDS.sleep(sleep);

        HttpGet get3 = new HttpGet("http://localhost:5003/service3");
        CloseableHttpResponse response3 = httpClient.execute(get3);
        String str3 = EntityUtils.toString(response3.getEntity(), "utf-8");

        HttpGet get4 = new HttpGet("http://localhost:5004/service4");
        CloseableHttpResponse response4 = httpClient.execute(get4);
        String str4 = EntityUtils.toString(response4.getEntity(), "utf-8");

        return str3 + " " + str4;
    }

    @GetMapping("/service3")
    public String service3() throws Exception {
        Random random = new Random();
        int sleep = random.nextInt(100);
        TimeUnit.MILLISECONDS.sleep(sleep);
        return "service3";
    }

    @GetMapping("/service4")
    public String service4() throws Exception {
        Random random = new Random();
        int sleep = random.nextInt(100);
        TimeUnit.MILLISECONDS.sleep(sleep);
        return "service4";
    }
}